package com.xpfirst.socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.xpfirst.ARMServerActivity;
import com.xpfirst.ActivityManage;

import android.util.Log;

public class SocketManage {
	private static Map<String,SocketClient> mapSocketClient = new HashMap<String,SocketClient>();
	private static Map<String,Thread> mapThread = new HashMap<String,Thread>();

	private static final int PORT  = 54321;
	private static SocketServer socketServer = null;
	private static Thread serverThread = null;
	public static void listen(){
		close();
        socketServer = new SocketServer();
        socketServer.PORT = PORT;
		serverThread = new Thread(socketServer);
		serverThread.start();
	}
	public static void close(){
		if(serverThread != null){
			socketServer.closeListen();
			serverThread.stop();
			serverThread = null;
			Iterator it = mapSocketClient.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				String host_ = (String)entry.getKey();
				SocketClient socketClient_ = (SocketClient)entry.getValue();
				if(socketClient_ != null){
					try {
						socketClient_.socket.close();
					} catch (IOException e) {
					}
					finally{
						mapSocketClient.remove(host_);
					}
				}
				Thread serverThread_ = mapThread.get(host_);
				if(serverThread_ != null){
					serverThread_.stop();
					mapThread.remove(host_);
				}
			}
			mapSocketClient.clear();
			mapThread.clear();
		}
	}
	public static void write(String str){
		   Iterator it = mapSocketClient.entrySet().iterator();
		   while (it.hasNext()) {
			    Map.Entry entry = (Map.Entry) it.next();
			    SocketClient value = (SocketClient)entry.getValue();
			    value.write(str);
			    ActivityManage.sendMsg(3, "sendMsg", str);
		   }
	}
	public static void creatSocketClient(Socket socket) {
		String host = socket.getInetAddress().getHostAddress();
		try
		{
            ActivityManage.sendMsg(2, "host", "creat:"+host);
			SocketClient socketClient = mapSocketClient.get(host);
			if(socketClient == null){
				socketClient = new SocketClient();
				socketClient.socket = socket;
				Thread serverThread_=new Thread(socketClient);
				serverThread_.start();
				
				mapSocketClient.put(host, socketClient);
				mapThread.put(host, serverThread_);
			}
		}
		catch(Exception ex)
		{
			removeSocketClient(host);
		}
	}
	public static void removeSocketClient(String host) {
        ActivityManage.sendMsg(2, "host", "remover:"+host);
		SocketClient socketClient_ = mapSocketClient.get(host);
		if(socketClient_ != null){
				mapSocketClient.remove(host);
		}
		Thread serverThread_ = mapThread.get(host);
		if(serverThread_ != null){
			if(serverThread_.isAlive()){
				serverThread_.stop();
			}
			mapThread.remove(host);
		}
	}
	public static String getLocalIpAddress() {   
	    try {   
	        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {   
	            NetworkInterface intf = en.nextElement();   
	            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {   
	                InetAddress inetAddress = enumIpAddr.nextElement();   
	                if (!inetAddress.isLoopbackAddress()) {   
	                    return inetAddress.getHostAddress().toString();   
	                }   
	            }   
	        }   
	    } catch (SocketException ex) {   
	        Log.e("exc", ex.toString());   
	    }   
	    return null;   
	}  
}
